package com.zFace.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 死锁示例
 */
public class DeadLock implements Runnable {
	private static ReentrantLock lock1 = new ReentrantLock();
	private static ReentrantLock lock2 = new ReentrantLock();

	private int lock;

	public DeadLock(int lock) {
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			if (lock == 1) {
				lock1.lock();
				Thread.sleep(1000);
				lock2.lock();
				System.out.println(Thread.currentThread().getName() + "，执行完毕！");
			} else {
				lock2.lock();
				Thread.sleep(1000);
				lock1.lock();
				System.out.println(Thread.currentThread().getName() + "，执行完毕！");
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (lock1.isHeldByCurrentThread()) {
				lock1.unlock();
			}
			if (lock2.isHeldByCurrentThread()) {
				lock2.unlock();
			}
			System.out.println(Thread.currentThread().getName() + "，退出。");
		}
	}

	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new DeadLock(1), "thread 1");
		Thread t2 = new Thread(new DeadLock(2), "thread 2");
		t1.start();
		t2.start();
	}
}
